import {
	login
} from '@/apis/login.js';
import { getRoutes, getOfToday } from '@/apis/user.js';
import {
	hanleToken
} from '@/utils/utils.js';
import config from '@/utils/config.js';
// #ifdef MP-WEIXIN
import * as Sentry from 'sentry-mina';
// #endif
const user = {
	namespaced: true,
	state: {
		token: '',
		userinfo: hanleToken('get', 'userinfo') || {},

		local: {

		},
		routes: hanleToken('get', 'routes') || [],
		routeCodes: hanleToken('get', 'routeCodes') || [],
		dataList: [],
		dataListPlus: [],

	},
	mutations: {
		setToken(state, token) {
			state.token = token;
		},
		setUserinfo(state, userinfo) {
			state.userinfo = userinfo; 
			hanleToken('set', 'userinfo',typeof userinfo == 'object' ? JSON.stringify(userinfo) : userinfo );

			// #ifdef MP-WEIXIN
			// 同步设置Sentry用户信息和tag
			if (userinfo && userinfo.user_id) {
				Sentry.configureScope(scope => {
					scope.setUser({ id: userinfo.user_id, name: userinfo.nick_name });
					scope.setTag('user_name', userinfo.nick_name); 
					scope.setTag('user_id', userinfo.user_id); 
				});
			} else {
				// 清除Sentry用户信息
				Sentry.configureScope(scope => {
					scope.setUser(null);
					scope.setTag('user_name', null);
					scope.setTag('user_id', null);
				});
			}
			 // #endif
		},
		setLocal(state, local) {
			state.local = local;
		},
		setRoutes(state, routes) {
			state.routes = routes;
			hanleToken('set', 'routes', JSON.stringify(routes));
		},
		setRouteCodes(state, routeCodes) {
			state.routeCodes = routeCodes;
			hanleToken('set', 'routeCodes', JSON.stringify(routeCodes));
		},
		logout(state) {
			state.token = '';
			state.userinfo = {};
		},
		dataListInfo(state, dataList) {
			state.dataList = dataList;
		},
		dataListInfoPlus(state, dataListPlus) {
			state.dataListPlus = dataListPlus;
		},
	},

	actions: {
		getRoutes({
			commit,
		}) {
			let codes = [];
			const findCodes = (arr) => {
				for (let i = 0; i < arr.length; i++) {
					codes.push(arr[i].code);
					if (arr[i].children && arr[i].children.length) {
						findCodes(arr[i].children);
					}
				}
			};
			return new Promise((resove) => {
				getRoutes().then(res => {
					commit('setRoutes', res.data || []);
					let list = res.data || [];
					findCodes(list);
					commit('setRouteCodes', codes || []);
					resove();
				}).catch(() => {
					resove();
				});
			});
		},

		reSetRoutes({
			commit,
		}) {
			commit('setRoutes', []);
			commit('setRouteCodes', []);
			console.log('Routes and RouteCodes reset.');
			return;
		},

		handleRreshToken({
			commit,
		}) {
			return new Promise((resove) => {
				const refreshTokenValue = hanleToken('get', 'refresh_token');
				if (!refreshTokenValue) {
					console.log('handleRreshToken: No refresh token found.');
					resove(false);
					return;
				}
				const params = {
					tenantId: config.tenantId,
					grant_type: 'refresh_token',
					scope: 'all',
					refresh_token: refreshTokenValue 
				};

				console.log(`handleRreshToken: Requesting with params: ${JSON.stringify(params)}`);

				login(params).then(res => {
					if (res.code === 200 && res.data) {
						console.log('handleRreshToken: Success', res.data);
						hanleToken('set', 'token', res.data.token_type + ' ' + res.data.access_token);
						hanleToken('set', 'refresh_token', res.data.refresh_token || '');
						hanleToken('set', 'userinfo', res.data || {});
						console.log(116,res.data);
						commit('setUserinfo', res.data || {});
						if (res.data && res.data.user_id) {
							resove(true);
						} else {
							console.warn('handleRreshToken: Token refreshed but user_id missing.');
							resove(false);
						}
					} else {
						console.error('handleRreshToken: Failed to refresh token', res);
						resove(false);
					}
				}).catch(err => {
					console.error('handleRreshToken: Network or other error', err);
					if (err.code == 400) {
						console.log('remove token', err);
						hanleToken('set', 'token', '');
						hanleToken('set', 'refresh_token', '');
						hanleToken('set', 'userinfo', '');
						commit('setUserinfo', { });
						resove(false);
					} else {
						resove(false);
					}
				});
			});
		},
		logoutFuc({
			commit,
		}) {
			console.log('Executing logoutFuc: Clearing user state and storage.');
			commit('setUserinfo', {});
			commit('setToken', '');
			hanleToken('remove', 'token');
			hanleToken('remove', 'refresh_token');
			commit('setRouteCodes', []);
			console.log('logoutFuc: User state and storage cleared.');
		},
		async getUserInfo({ commit, state }) {
			const userData = await hanleToken('get', 'userData');
			if (userData) { 
				console.log(158,userData);
				commit('setUserinfo',userData);
			}
		},
		async getPlanLatitudePlus({ commit }, buildingIds = '') {
			let res = await Promise.all([getOfToday({ buildingIds })]);
			if (res[0].code == 200) {
				let dataListPlus = res[0].data || [];
				commit('dataListInfoPlus', dataListPlus);
				return dataListPlus;
			}
			return [];
		},

		async getPlanLatitude({ commit }, buildingIds = '') {
			let res = await Promise.all([getOfToday({ buildingIds })]);
			if (res[0].code == 200) {
				let dataList = res[0].data || [];
				dataList.forEach(item => {
					item.planSignM = 500;
					item.planSignOutM = 500;
				});
				commit('dataListInfo', dataList);
				return dataList;
			}
			return [];
		}

	}
};

export default user;
